package au.edu.uq.itee.engg2800.team19;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;



public class JHyperProtocol implements RS232Protocol,Subject {

	byte[] buffer = new byte[1024];
	//int freqCounter =1;
    int tail = 0;
    private String messageIn;
    private List<Observer> freqlist = new  ArrayList<Observer>();
    private FrequenciesReceived freq;
    public JHyperProtocol(FrequenciesReceived freqs){
    	this.freq=freqs;
	}

    public void onReceive(byte b) {
        // simple protocol: each message ends with new line
        if (b=='\n') {

            onMessage();
            notifyListeners();

        } else {
            buffer[tail] = b;
            tail++;
        }
    }

    public void onStreamClosed() {
        onMessage();
    }

    /*
     * When message is recognized onMessage is invoked
     */
    private void onMessage() {
        if (tail!=0) {
            // constructing message
            String message = getMessage(buffer, tail);

            System.out.println("RECEIVED MESSAGE: " + message);
            this.messageIn=message;
            	String temp=message.trim();
            	freq.updateMap( Integer.parseInt(temp));
            tail = 0;
        }
    }

    // helper methods
    public byte[] getMessage(String message) {
        return (message+"\n").getBytes();
    }

    public String getMessage(byte[] buffer, int len) {
        return new String(buffer, 0, tail);
    }


	@Override
	public void addListener(Observer o) {
		this.freqlist.add(o);

	}


	@Override
	public void removeListener(Observer o) {
		// TODO Auto-generated method stub
		this.freqlist.remove(o);
	}


	@Override
	public void notifyListeners() {
		 for (Iterator<Observer> iter = freqlist.iterator(); iter.hasNext();) {
			   Observer listener = (Observer) iter.next();
			   listener.update(this.messageIn);

	}
	}
}
